package com.nave.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class Database
{	
	private final static String TABLE_NAME= "scores";
	private final static String DATABASE_NAME = "nave_database";
	private final static int DATABASE_VERSION = 1;

	public final static String KEY_ID = "_id";
	public final static String KEY_NAME = "name";
	public final static String KEY_POINTS = "points";

	private final static String ORDER_BY = KEY_POINTS + " DESC";
	
	private static final String DATABASE_CREATE = "CREATE TABLE " +
		TABLE_NAME + " (" +
        KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
        KEY_NAME + " TEXT NOT NULL, " + 
        KEY_POINTS + " INTEGER);";

	private SQLiteDatabase database;
	
//	private Cursor cursor;
	private final Context context;
	private DatabaseHelper DBHelper;
	
	public Database(Context ctx)
	{
		context = ctx;
		DBHelper = new DatabaseHelper(context);
	}
	
	private static class DatabaseHelper extends SQLiteOpenHelper 
    {	
        DatabaseHelper(Context context) 
        {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
        @Override
        public void onCreate(SQLiteDatabase db)
        {
            db.execSQL(DATABASE_CREATE);
        }
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, 
        int newVersion) 
        {
            Log.w("NAVE", "Upgrading database from version " + oldVersion 
                    + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
            onCreate(db);
        }
    }

	//---opens the database---
    public Database open() throws SQLException 
    {
        database = DBHelper.getWritableDatabase();
        return this;
    }
    //---closes the database---    
    public void close() 
    {
        DBHelper.close();
    }
    //---retrieves all the titles---
    public Cursor getAllTitles() 
    {
        return database.query(TABLE_NAME, null, null, null, null, null, ORDER_BY);
    }
    //---insert a title into the database---
    public void insertRecord(String name, int points) 
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, name);
        initialValues.put(KEY_POINTS, points);
        
        database.insert(TABLE_NAME, null, initialValues);
    }
    public void clear() {
    	database.delete(TABLE_NAME, null, null);
    }
}